package com.linjiahao.userCenter.controller;

import com.linjiahao.servicebase.common.BaseConstant;
import com.linjiahao.servicebase.common.ResultMap;
import com.linjiahao.servicebase.exception.ErrorMessage;
import com.linjiahao.servicebase.exception.WebChatException;
import com.linjiahao.servicebase.util.JWTUtil;
import com.linjiahao.userCenter.service.ChatUserInfoService;
import com.linjiahao.userCenter.util.MsmSendUtil;
import com.linjiahao.userCenter.vo.PersonInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @ClassName ChatUserInfoController
 * @Description: 用户服务控制层
 * @Author linjiahao
 * @Date 29/12/2021
 **/
@RestController
@Slf4j
@RequestMapping("/userCenter/user")
public class ChatUserInfoController {

    @Resource
    private MsmSendUtil msmSendUtil;

    @Autowired
    private ChatUserInfoService userInfoService;


    @GetMapping("/getMsmCode")
    public ResultMap getMsmCode(@RequestParam("phone") String phone){
        boolean msm = msmSendUtil.sendMsm(phone);
        if(msm){
            return ResultMap.ok().message("发送成功");
        }
        return ResultMap.error();
    }

    @GetMapping("/login")
    public ResultMap userLogin(@RequestParam("phone") String phone, @RequestParam("code") String code,HttpServletResponse response){
        if(StringUtils.isBlank(phone) || StringUtils.isBlank(code) ){
            throw new WebChatException(ErrorMessage.PARAMETER_CANNOT_EMPTY.getErrorCode(),ErrorMessage.PARAMETER_CANNOT_EMPTY.getMessage());
        }
        return userInfoService.userLogin(phone,code,response);
    }

    @GetMapping("/logout")
    public ResultMap logout(HttpServletRequest request){
        String authToken = request.getHeader(BaseConstant.HEADER_TOKEN_KEY);
        userInfoService.logout(authToken);
        return ResultMap.ok();
    }

    @GetMapping("/auth/getUserInfoBytoken")
    public ResultMap getUserInfoBytoken(HttpServletRequest request){
        String authToken = request.getHeader(BaseConstant.HEADER_TOKEN_KEY);
        return userInfoService.getUserInfoBytoken(authToken);
    }

    @PostMapping("/auth/searchPerson")
    public ResultMap searchPerson(@RequestParam String keyWord,HttpServletRequest request){
        if(StringUtils.isBlank(keyWord) ){
            throw new WebChatException(ErrorMessage.PARAMETER_CANNOT_EMPTY.getErrorCode(),ErrorMessage.PARAMETER_CANNOT_EMPTY.getMessage());
        }
        List<PersonInfoVO> list = userInfoService.searchPerson(keyWord, JWTUtil.getUserId(request));
        return ResultMap.ok().data("list",list);
    }

}
